/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.datamanager.rest;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ibm.iisp.common.vo.PagedQueryResult;
import com.ibm.iisp.common.web.utils.WebUtils;
import com.ibm.iisp.data.model.DataTable;
import com.ibm.iisp.data.model.DataTableColumn;
import com.ibm.iisp.datamanager.service.DataManagerService;
import com.ibm.iisp.datamanager.vo.DataTableQueryParam;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
@RestController
@RequestMapping("/iisp-data-mgr")
public class DataManagerResource {
	Logger log = LoggerFactory.getLogger(getClass());
	@Inject
	DataManagerService service;
	@Context
	HttpServletRequest request;

	@GetMapping("/data-tables")
	public List<DataTable> getDataTables(@RequestParam("tableCode") String tableCode) {
		List<DataTable> dataTables = service.getDataTables(tableCode);
		for (DataTable dt : dataTables) {
			dt.setColumns(null);
		}
		return dataTables;
	}

	@GetMapping("/data-tables/{tableCode}")
	public DataTable getDataTable(@PathVariable("tableCode") String tableCode) {
		DataTable dataTable = service.getDataTable(tableCode);
		for (DataTableColumn col : dataTable.getColumns()) {
			if (col.getOptions() != null && col.getOptions().isEmpty()) {
				col.setOptions(null);
			}
		}
		return dataTable;
	}

	@GetMapping("/datas/data-tables/{tableCode}")
	public PagedQueryResult<?> getDataTableData(@PathVariable("tableCode") String tableCode) {
		DataTableQueryParam param = WebUtils.getRequestObject(DataTableQueryParam.class, request);
		if (param == null) {
			param = new DataTableQueryParam();
		}
		param.setTableCode(tableCode);
		Enumeration<String> names = request.getParameterNames();
		param.setParams(new HashMap<String, Object>());
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			param.getParams().put(name, request.getParameter(name));
		}

		return service.getTableData(param);
	}

}
